package com.netty.source_code.transport;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * @author xl-9527
 * @since 2025/7/13
 **/
public class HttpServer {

    private static final Logger log = LoggerFactory.getLogger(HttpServer.class);

    public static void main(String[] args) throws InterruptedException {
        new HttpServerBootStrap().bind(8080);
    }

    private static class HttpServerBootStrap {

        private final ServerBootstrap serverBootstrap;

        public HttpServerBootStrap() {
            this.serverBootstrap = new ServerBootstrap()
                    .group(new NioEventLoopGroup(3))
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(final NioSocketChannel ch) {
                            final ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("codec", new HttpServerCodec())
                                    .addLast("compress", new HttpContentCompressor())
                                    .addLast("aggregator", new HttpObjectAggregator(65536))
                                    .addLast("handler", new HttpServerHandler());
                            // 异常拦截器
                            pipeline.addLast(new ExceptionHandler());
                        }
                    });
        }

        public void bind(int port) throws InterruptedException {
            final ChannelFuture sync = serverBootstrap.bind(port).sync();
            sync.addListener(future -> {
                if (future.isSuccess()) {
                    log.info("启动成功，端口：{}", port);
                }
            }).sync();
        }

        /**
         * exception 拦截器
         */
        private static class ExceptionHandler extends ChannelDuplexHandler {

            @Override
            public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
                log.error("异常：{}", cause.getMessage());
                ctx.channel().close();
            }
        }

        /**
         * 处理器
         */
        private static class HttpServerHandler extends ChannelInboundHandlerAdapter {

            @Override
            public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
                log.info("写的消息：{}", msg);
                final DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(
                        HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                        ctx.alloc().directBuffer().writeBytes("你好".getBytes(StandardCharsets.UTF_8))
                );
                ctx.channel().writeAndFlush(httpResponse);
            }
        }
    }
}
